package server;

import com.sun.xml.internal.ws.resources.SenderMessages;

import java.io.*;
import java.net.Socket;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Client {
    private volatile String name;
    private DataInputStream dataInputStream;
    private DataOutputStream dataOutputStream;
    private Socket socket;
    private ConcurrentLinkedQueue<String> localMessageQueue;
    private MessageProcessor messageProcessor;
    private volatile boolean newClient = true;
    private volatile String room;
    private Server server;


    public Client(Socket socket, Server server) throws IOException {
        this.socket = socket;
        this.server = server;
        messageProcessor = new MessageProcessor(server);
        localMessageQueue = new ConcurrentLinkedQueue<>();
    }

    public void startCommunicate() throws IOException {
        dataInputStream = new DataInputStream(socket.getInputStream());
        dataOutputStream = new DataOutputStream(socket.getOutputStream());
        sendMessage("Use \"/chid <your_name> <password>\" to sign in, or use \"/reg <your_name> <password>\" to register");
        new Thread() {
            @Override
            public void run() {
                while (true) {
                    try {
                        if (dataInputStream.available() > 0)
                            messageProcessor.process(Client.this, dataInputStream.readUTF());
                        if (!localMessageQueue.isEmpty()) {
                            dataOutputStream.writeUTF(localMessageQueue.poll());
                            dataOutputStream.flush();
                        }
                    } catch (IOException e) {
                        server.removeClientFromChat(this.getName());
                    }
                }
            }
        }.start();
    }

    public void sendMessage(String message) {
        localMessageQueue.add(message);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }

    public boolean isNewClient() {
        return newClient;
    }

    public void setNewClient(boolean newClient) {
        this.newClient = newClient;
    }

    public String getRoom() {
        return room;
    }

    public void setRoom(String room) {
        this.room = room;
    }
}